﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.UI.WebControls;
using DynamicComparer;
using Shuba.Model;

namespace Shuba.Web.master
{
    public partial class topup_list : basePage
    {
        string msg = "";
        bool IsView, IsAdd, IsEdit, IsDelete, IsChecker;
        const int rowsPerPage = 20;
        string currentPage;
        int jmlRow;

        const int rowsPerPage2 = 20;
        string currentPage2;
        int jmlRow2;
       

        protected void Page_Load(object sender, EventArgs e)
        {
            Form.DefaultFocus = txtSearch.ClientID;
            Form.DefaultButton = btnSearch.UniqueID;

            string acl = GetUserAccess("MSTR_TOPUP");
            IsView = IsUserView(acl);
            IsAdd = IsUserAdd(acl);
            IsEdit = IsUserEdit(acl);
            IsDelete = IsUserDelete(acl);
            IsChecker = IsUserChecker(acl);

            if (!IsView)
            {
                msg = GetGlobalResourceObject("Messages", "NoPrivilege").ToString();
                AlertAndRedirect(msg, ResolveUrl(ConfigurationManager.AppSettings["default_url"]));
            }

            if (!IsPostBack)
            {
                
                InitSort();
                ViewState["searchBy"] = "";
                currentPage = "1";
                currentPage2 = "1";

                ViewState["SortEx"] = "UPDATE_DATE";
                ViewState["Sort"] = "ASC";

                ViewState["SortEx2"] = "UPDATE_DATE";
                ViewState["Sort2"] = "DESC";

                BindData();

                LabelTitle.Text = GetPageTitle("MSTR_TOPUP");

                //if (IsAdd) btnUpload.Enabled = true; else btnUpload.Enabled = false;
            }
        }

        private void BindData()
        {
            Shuba.Business.TopUp BI = new Shuba.Business.TopUp();
            List<TopUpInfo> list;

            if (ddlTopUpPage.Items.Count == 0 || ViewState["searchBy"].ToString() != txtSearch.Text)
                currentPage = "1";
            else currentPage = ddlTopUpPage.SelectedValue;            

            jmlRow = BI.GetRowNumber(txtSearch.Text);

            list = BI.GetList(txtSearch.Text, int.Parse(currentPage), rowsPerPage);
            ViewState["List"] = list;
            
            gvList.DataSource = list;
            gvList.DataBind();
            load_data_topup_page();

            if (IsDelete) gvList.Columns[gvList.Columns.Count - 1].Visible = true;
            else gvList.Columns[gvList.Columns.Count -1].Visible = false;

            //FOR APPROVAL GRID
            if (IsChecker)
            {
                BindApprovalData();
                if (ApprovalGrid.Rows.Count > 0) { ApprovalPnl.Visible = true; } else { ApprovalPnl.Visible = false; }
            }
        }

        protected void load_data_topup_page()
        {
            Shuba.Business.TopUpBulk topupBisnis = new Shuba.Business.TopUpBulk();
            int jmlHal = (int)Math.Ceiling((decimal)jmlRow / (decimal)rowsPerPage);
            string pageNum;

            footLink.Visible = (jmlHal > 0);

            ddlTopUpPage.Items.Clear();
            for (int i = 0; i < jmlHal; i++)
            {
                pageNum = (i + 1).ToString();
                ddlTopUpPage.Items.Add(new ListItem(pageNum, pageNum));
            }

            if (ViewState["searchBy"].ToString() == txtSearch.Text)
                ddlTopUpPage.SelectedValue = currentPage;
            ViewState["searchBy"] = txtSearch.Text;

            lblPage.Text = "Page " + currentPage + " of " + jmlHal;

            firstLink.Visible = true;
            prevLink.Visible = true;
            nextLink.Visible = true;
            lastLink.Visible = true;

            if (ddlTopUpPage.SelectedIndex <= 0)
            {
                firstLink.Visible = false;
                prevLink.Visible = false;
            }
            if (ddlTopUpPage.SelectedIndex >= ddlTopUpPage.Items.Count - 1)
            {
                nextLink.Visible = false;
                lastLink.Visible = false;
            }
        }

        protected void ddlTopUpPage_IndexChange(object sender, EventArgs e)
        {
            BindData();
        }

        protected void linkDataPage_Click(object sender, EventArgs e)
        {
            if (sender == firstLink)
                ddlTopUpPage.SelectedIndex = 0;
            else if (sender == prevLink)
                ddlTopUpPage.SelectedIndex--;
            else if (sender == nextLink)
                ddlTopUpPage.SelectedIndex++;
            else if (sender == lastLink)
                ddlTopUpPage.SelectedIndex = ddlTopUpPage.Items.Count - 1;
            BindData();
        }

        protected void gvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvList.PageIndex = e.NewPageIndex;
            BindData();
        }

        protected void gvList_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            gvList.PageIndex = 0;

            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                List<TopUpInfo> list = (List<TopUpInfo>)ViewState["List"];

                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<TopUpInfo> comparer = new DynamicComparer<TopUpInfo>(sort);
                list.Sort(comparer);

                gvList.DataSource = list;
                gvList.DataBind();
            }
        }

        protected void gvList_RowDataBound(object sender, GridViewRowEventArgs e)
        {            
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton btnDelete = (LinkButton)e.Row.FindControl("btnDelete");

                if (IsDelete)
                {
                    //btnDelete.Enabled = true;
                }
                else
                {
                   // btnDelete.Enabled = false;
                    //btnDelete.OnClientClick = "";
                }
                if (e.Row.Cells[13].Text.ToLower().Contains("01 jan 2009")) e.Row.Cells[13].Text = "";
                //if (e.Row.Cells[5].Text.ToLower() == "false") e.Row.Cells[6].Text = "";
            }
        }

        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Remove")
            {
                string[] ParamID = e.CommandArgument.ToString().Split('~');
                string CIF_NUMBER = ParamID[0].ToString().Trim();
                string LOAN_NUMBER = ParamID[1].ToString().Trim();

                Shuba.Business.TopUp BI = new Shuba.Business.TopUp();
                TopUpInfo BIInfo = BI.Get(CIF_NUMBER, LOAN_NUMBER);

                BIInfo.UPDATE_BY = HttpContext.Current.User.Identity.Name;
                BIInfo.UPDATE_DATE = ProcessingDate();
                BIInfo.ACT_TYPE = "DELETE";

                try
                {
                    BI.Save(BIInfo);
                    AddLog("DELETE", "DELETE TOPUP");
                }
                catch (Exception ex)
                {
                    msg = ex.Message.ToString();
                    ErrBox.Visible = true;
                    ErrMsg.Text = msg;
                }

                if (msg == "") RestartPage();
            }
        }


        protected void btnSearch_Click(object sender, EventArgs e)
        {
            BindData();
        }


        /*======================================
               APPROVAL GRID START HERE
        =======================================
        */
        private void BindApprovalData()
        {
            Shuba.Business.TopUp BI = new Shuba.Business.TopUp();
            List<TopUpInfo> list;
            
            if (ddlApproval.Items.Count == 0)
                currentPage2 = "1";
            else currentPage2 = ddlApproval.SelectedValue;

            list = BI.GetListApproval(HttpContext.Current.User.Identity.Name, int.Parse(currentPage2), rowsPerPage2);
            jmlRow2 = BI.GetListApprovalNumber(HttpContext.Current.User.Identity.Name);

            ViewState["ListApproval"] = list;

            load_data_Approval_page();
            ApprovalGrid.DataSource = list;
            ApprovalGrid.DataBind();
        }

        // start ++
        protected void load_data_Approval_page()
        {
            int jmlHal = (int)Math.Ceiling((decimal)jmlRow2 / (decimal)rowsPerPage2);
            string pageNum;

            footLinkApproval.Visible = (jmlHal > 0);

            ddlApproval.Items.Clear();
            for (int i = 0; i < jmlHal; i++)
            {
                pageNum = (i + 1).ToString();
                ddlApproval.Items.Add(new ListItem(pageNum, pageNum));
            }

            ddlApproval.SelectedValue = currentPage2;
            lblPageApproval.Text = "Page " + currentPage2 + " of " + jmlHal;

            firstLinkApproval.Visible = true;
            prevLinkApproval.Visible = true;
            nextLinkApproval.Visible = true;
            lastLinkApproval.Visible = true;

            if (ddlApproval.SelectedIndex <= 0)
            {
                firstLinkApproval.Visible = false;
                prevLinkApproval.Visible = false;
            }

            if (ddlApproval.SelectedIndex >= ddlApproval.Items.Count - 1)
            {
                nextLinkApproval.Visible = false;
                lastLinkApproval.Visible = false;
            }
        }

        protected void ddlApproval_IndexChange(object sender, EventArgs e)
        {
            BindApprovalData();
        }

        protected void linkDataApprovalPage_Click(object sender, EventArgs e)
        {
            if (sender == firstLinkApproval)
                ddlApproval.SelectedIndex = 0;
            else if (sender == prevLinkApproval)
                ddlApproval.SelectedIndex--;
            else if (sender == nextLinkApproval)
                ddlApproval.SelectedIndex++;
            else if (sender == lastLinkApproval)
                ddlApproval.SelectedIndex = ddlApproval.Items.Count - 1;
            BindData();
        }
        // end ++

        protected void ApprovalGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            ApprovalGrid.PageIndex = e.NewPageIndex;
            BindApprovalData();
        }

        protected void ApprovalGrid_Sorting(object sender, GridViewSortEventArgs e)
        {
            SortDirection(e.SortExpression, e.SortDirection.ToString());
            ViewState["SortEx"] = e.SortExpression;
            ApprovalGrid.PageIndex = 0;

            if (ViewState["SortEx"].ToString().Trim() != "")
            {
                List<TopUpInfo> list = (List<TopUpInfo>)ViewState["ListApproval"];

                string sort = sort = ViewState["SortEx"].ToString() + " " + ViewState["Sort"];
                DynamicComparer<TopUpInfo> comparer = new DynamicComparer<TopUpInfo>(sort);
                list.Sort(comparer);

                ApprovalGrid.DataSource = list;
                ApprovalGrid.DataBind();
            }
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            int ErrorCount = 0, SuccessCount = 0;

            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");

                if (chkItemSelect.Checked)
                {
                    string CIF_NUMBER = ApprovalGrid.DataKeys[row.RowIndex].Value.ToString();
                    string LOAN_NUMBER = ApprovalGrid.DataKeys[row.RowIndex].Values["LOAN_NUMBER"].ToString();                    

                    if (Approve(CIF_NUMBER, LOAN_NUMBER, true))
                    {
                        SuccessCount++;
                    }
                    else
                    {
                        ErrorCount++;
                    }
                }
            }
            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nSuccessfully Approve : " + SuccessCount + " Record(s)\\n\\nFailed to Approve : " + ErrorCount + " Record(s)";
            }            
            BindData();
            Alert(msg);
            //msg = this.GetGlobalResourceObject("Messages", "ApproveAlert").ToString();
            //AlertAndRedirect(msg, Request.Url.PathAndQuery);
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            int ErrorCount = 0, SuccessCount = 0;

            foreach (GridViewRow row in ApprovalGrid.Rows)
            {
                CheckBox chkItemSelect = (CheckBox)row.FindControl("chkItemSelect");

                if (chkItemSelect.Checked)
                {
                    string CIF_NUMBER = ApprovalGrid.DataKeys[row.RowIndex].Value.ToString();
                    string LOAN_NUMBER = ApprovalGrid.DataKeys[row.RowIndex].Values["LOAN_NUMBER"].ToString(); 

                    if (Approve(CIF_NUMBER, LOAN_NUMBER, false))
                    {
                        SuccessCount++;
                    }
                    else
                    {
                        ErrorCount++;
                    }
                }
            }
            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nSuccessfully Reject : " + SuccessCount + " Record(s)\\n\\nFailed to Reject : " + ErrorCount + " Record(s)";
            }        
            BindData();
            Alert(msg);
            //AlertAndRedirect(msg, Request.Url.PathAndQuery);
            //msg = this.GetGlobalResourceObject("Messages", "NoApprove").ToString();
        }

        private bool Approve(string CIF_NUMBER, string LOAN_NUMBER, bool IsApprove)
        {
            bool approve = false;
            string ActType = "INSERT";

            Shuba.Business.TopUp BI = new Shuba.Business.TopUp();
            TopUpInfo BIInfo = new TopUpInfo();

            CIF_NUMBER = Server.HtmlDecode(CIF_NUMBER).Trim(); //CIF_NUMBER.Replace("&nbsp;", "");
            LOAN_NUMBER = Server.HtmlDecode(LOAN_NUMBER).Trim(); //LOAN_NUMBER.Replace("&nbsp;", "");

            BIInfo = BI.GetApprovalByID(CIF_NUMBER, LOAN_NUMBER);
            ActType = BIInfo.ACT_TYPE;
            BIInfo.UPDATE_BY = HttpContext.Current.User.Identity.Name;
            BIInfo.UPDATE_DATE = ProcessingDate();

            if (IsApprove)
            {
                if (BIInfo.CIF_NUMBER != "" && BIInfo.LOAN_NUMBER != "")
                {
                    try
                    {
                        AddLog("APPROVAL", "APPROVE TOPUP");
                        if (BI.Approve(CIF_NUMBER, LOAN_NUMBER, ActType) > 0)
                        {
                            approve = true;
                        }
                        else
                        {
                            approve = false;
                        }
                    }
                    catch (Exception ex)
                    {
                        approve = false;
                        ErrBox.Visible = true;
                        ErrMsg.Text = ex.Message;
                    }
                }
            }
            else
            {
                AddLog("APPROVAL", "REJECT TOPUP");
                if (BI.Reject(CIF_NUMBER, LOAN_NUMBER) > 0)
                {
                    approve = true;
                }
                else
                {
                    approve = false;
                }
            }
            return approve;
        }

        protected void btnApproveAll_Click(object sender, EventArgs e)
        {
            int ErrorCount = 0, SuccessCount = 0;

            Shuba.Business.TopUp BI = new Shuba.Business.TopUp();
            List<TopUpInfo> list = BI.GetListApproval(HttpContext.Current.User.Identity.Name);

            foreach (TopUpInfo item in list)
            {
                try
                {
                    if (Approve(item.CIF_NUMBER, item.LOAN_NUMBER, true))
                    {
                        SuccessCount++;
                    }
                    else
                    {
                        ErrorCount++;
                    }
                }
                catch (Exception)
                {
                    ErrorCount++;
                }
            }
            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nTotal record to approve : " + list.Count + "Record(s)\\nSuccessfully Approve : " + SuccessCount + " Record(s)\\nFailed to Approve : " + ErrorCount + " Record(s)";
            }
            BindData();
            Alert(msg);
        }

        protected void btnRejectAll_Click(object sender, EventArgs e)
        {
            int ErrorCount = 0, SuccessCount = 0;

            Shuba.Business.TopUp BI = new Shuba.Business.TopUp();
            List<TopUpInfo> list = BI.GetListApproval(HttpContext.Current.User.Identity.Name);

            foreach (TopUpInfo item in list)
            {
                try
                {
                    if (Approve(item.CIF_NUMBER, item.LOAN_NUMBER, false))
                    {
                        SuccessCount++;
                    }
                    else
                    {
                        ErrorCount++;
                    }
                }
                catch (Exception)
                {
                    ErrorCount++;
                }
            }
            if (SuccessCount > 0 || ErrorCount > 0)
            {
                msg = "Approval Notification\\n\\nTotal record to reject : " + list.Count + "Record(s)\\nSuccessfully Reject : " + SuccessCount + " Record(s)\\nFailed to Reject : " + ErrorCount + " Record(s)";
            }
            BindData();
            Alert(msg);
        }
    }
}
